package com.endoc.news.fragment.base;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;


/*
* BaseCustomView的封装逻辑
* 1.因为用到DataBinding,所以需要有databinding类的变量,由子类实现提供
* 2.因为需要用到数据,那么需要ViewModel的变量,由外部提供
* 3.继承IbaseCustomView,此接口是提供setData(ViewModel),提供viewModel实例对象
* */
public abstract class BaseCustomView<TViewBinding extends ViewDataBinding,TViewModel extends BaseViewModel> extends LinearLayoutCompat  implements IBaseCustomView<TViewModel> {
    public TViewBinding mViewBinding;//布局对应的viewBinding
    public TViewModel mTViewModel;//viewModel对象
    public BaseCustomView(@NonNull Context context) {
        super(context);
        init();
    }

    public BaseCustomView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BaseCustomView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        View inflate = LayoutInflater.from(getContext()).inflate(getResourceId(), this, false);
        mViewBinding = DataBindingUtil.bind(inflate);

      /*  LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mViewBinding = DataBindingUtil.inflate(inflater, getResourceId(), this, false);*/
        mViewBinding.getRoot().setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onclick(v);
            }
        });
        addView(mViewBinding.getRoot());
    }

    @Override
    public void setData(TViewModel viewModel) {
        setViewModelToView(viewModel);
        mTViewModel =viewModel;//设置viewModel
        mViewBinding.executePendingBindings();//不知道为什么需要这样写
    }


  /*  public  void setViewModel(TViewModel tViewModel){
        setViewModelToView(tViewModel);
        mTViewModel =tViewModel;//设置viewModel
        mViewBinding.executePendingBindings();
    }*/


    public  abstract  void setViewModelToView(TViewModel tViewModel);

    public abstract int  getResourceId();

    public abstract void   onclick(View v);

}
